package com.mszlu.blog.handler;

import com.alibaba.fastjson.JSON;
import com.mszlu.blog.common.Result;
import com.mszlu.blog.common.SysUserThreadLocal;
import com.mszlu.blog.entity.SysUser;
import com.mszlu.blog.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginIntercepter implements HandlerInterceptor {

    @Autowired
    private LoginService loginService;

    @Override//在执行方法之前执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断访问的是controller方法
        if (!(handler instanceof HandlerMethod)) {
            //handler可能是访问静态资源的RequestResourceHandler
            return true;
        }
        //判断token是否为空,如果为空,未登录
        String token = request.getHeader("Authorization");


        log.info("================request start==================");
        String requestURL = request.getRequestURI();
        log.info("request url:{}",requestURL);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}",token);
        log.info("================request end==================");

        if (StringUtils.isBlank(token)){
            Result<Object> result = Result.loginError("未登录");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        //如果token不为空,进行登录验证checkToken
        SysUser user = loginService.checkLogin(token);
        if (user == null){
            Result<Object> result = Result.loginError("未登录");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        //认证成功，放行
        SysUserThreadLocal.put(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        SysUserThreadLocal.remove();

    }
}
